package com.arpa.wms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.GoodsDTO;
import com.arpa.wms.domain.dto.GoodsExcelDTO;
import com.arpa.wms.domain.entity.Goods;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.GoodsExcelVO;
import com.arpa.wms.domain.vo.GoodsVO;
import com.arpa.wms.service.IGoodsService;
import com.arpa.wms.service.IGoodsTypeService;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: Allen chen
 * @Date 2020/8/12
 * @Description: 商品管理 controller
 */
@Api(tags = "商品")
@RestController
@RequestMapping(value = "/goods", produces = "application/json;charset=UTF-8")
@Log4j2
public class GoodsController {

    private final IGoodsService iGoodsService;

    private final IGoodsTypeService iGoodsTypeService;

    public GoodsController(IGoodsService iGoodsService, IGoodsTypeService iGoodsTypeService) {
        this.iGoodsService = iGoodsService;
        this.iGoodsTypeService = iGoodsTypeService;
    }

    private final static String BR_FONT_COLOR_RED_GOODS = "<br><font color='red'>商品【";

    @ApiOperation(value = "模糊查询货主商品", notes = "模糊查询货主商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "keywords", value = "商品名称、编码、条码", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "shipmentCode", value = "货主code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/search")
    public Result search(@RequestParam(value = "keywords",defaultValue = "") String keywords,@RequestParam(value = "shipmentCode",required = true) String shipmentCode, HttpServletRequest request) {
        try {
            List<Map<String, Object>> result = iGoodsService.search(keywords,shipmentCode);
            return Result.ok().data(result);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取 商品 列表", notes = "获取 商品 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = GoodsVO.class))
    @NeedLogin
    @GetMapping
    public Result list(GoodsDTO unitDTO, HttpServletRequest request) {
        try {
            // 根据商品分类查询是否有子类
            List<String> codes = new ArrayList<>();
            codes.add(unitDTO.getTypeCode());
            iGoodsTypeService.listByShipmentCode(codes, unitDTO.getTypeCode(), unitDTO.getShipmentCode());
            unitDTO.setList(codes);
            unitDTO.setTypeCode(StrUtil.EMPTY);
            unitDTO.setRecordType(0);
            GoodsVO unitSum = iGoodsService.queryListSum(unitDTO);
            //所属机构过滤
            unitDTO.setPartyGroupCode(UserUtil.getBranchCode());
            List<GoodsVO> unitVOList = iGoodsService.queryList(unitDTO);

            Page returnPage = new Page(unitDTO.getPageNum(), unitDTO.getPageSize());
            returnPage.setRecords(unitVOList);
            returnPage.setTotal(unitSum.getTotal());
            returnPage.setSumObject(unitSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "添加 商品 ", notes = "添加 商品 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping
    public Result create(@Valid @RequestBody Goods goods, HttpServletRequest request) {
        try {
            if (goods != null && IterUtil.isNotEmpty(goods.getGoodsUnitConversionList())) {
                goods.setRecordType(0);
                iGoodsService.save(goods);
                return Result.ok("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取商品详情", notes = "获取商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "商品标识", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = GoodsVO.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result detail(@PathVariable String code, HttpServletRequest request) {
        try {
            GoodsDTO dto = new GoodsDTO();
            dto.setCode(code);
            GoodsVO goodsVO = iGoodsService.detailWithUnitConversion(dto);
            return Result.ok().data(goodsVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "修改商品", notes = "修改商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping
    public Result update(@RequestBody Goods goods, HttpServletRequest request) {
        if (null == goods || IterUtil.isEmpty(goods.getGoodsUnitConversionList())) {
            return Result.error("数据不能为空");
        }
        iGoodsService.updateByCode(goods);
        return Result.ok("修改成功");
    }

    @ApiOperation(value = "删除商品信息", notes = "删除商品信息", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "codes", value = "商品标识", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping("batchdel")
    public Result delete(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            Map<String, Object> result = iGoodsService.removeByCodes(codes);
            Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
            List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
            int failNum = codes.size() - success;
            StringBuilder buffer = new StringBuilder();
            buffer.append("删除成功").append(success).append("条；失败").append(failNum).append("条；");
            if(IterUtil.isNotEmpty(notDelete)){
                for (String m:notDelete) {
                    buffer.append(BR_FONT_COLOR_RED_GOODS).append(m).append("】删除失败，已被启用过;</font>");
                }
            }
            return Result.ok(buffer.toString());
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "启用商品", notes = "启用商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iGoodsService.batchUpdateStatus(codes, StatusEnum.ACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    @ApiOperation(value = "停用商品", notes = "停用商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = iGoodsService.batchUpdateStatus(codes, StatusEnum.UNACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        List<String> quantityUse = MapUtil.get(result, "quantityUse", List.class);
        List<String> receiveUse = MapUtil.get(result, "receiveUse",List.class);
        List<String> initUse = MapUtil.get(result, "initUse",List.class);
        List<String> countingUse = MapUtil.get(result, "countingUse",List.class);
        List<String> diffUse = MapUtil.get(result, "diffUse",List.class);
        StringBuilder message = new StringBuilder();
        if(IterUtil.isNotEmpty(quantityUse)){
            for(String m: quantityUse){
                message.append(BR_FONT_COLOR_RED_GOODS).append(m).append("】停用失败，库存不为0;</font>");
            }
        }
        if(IterUtil.isNotEmpty(receiveUse)){
            for(String m: receiveUse){
                message.append(BR_FONT_COLOR_RED_GOODS).append(m).append("】停用失败，收货单正在使用中;</font>");
            }
        }
        if(IterUtil.isNotEmpty(initUse)){
            for(String m: initUse){
                message.append(BR_FONT_COLOR_RED_GOODS).append(m).append("】停用失败，期初单正在使用中;</font>");
            }
        }
        if(IterUtil.isNotEmpty(countingUse)){
            for(String m: countingUse){
                message.append(BR_FONT_COLOR_RED_GOODS).append(m).append("】停用失败，盘点单正在使用中;</font>");
            }
        }
        if(IterUtil.isNotEmpty(diffUse)){
            for(String m: diffUse){
                message.append(BR_FONT_COLOR_RED_GOODS).append(m).append("】停用失败，差异单正在使用中;</font>");
            }
        }
        return Result.ok("停用成功" + success + "条；失败" + (codes.size() - success) + "条；"+message.toString());
    }

    @ApiOperation(value = "商品 导入 预览", notes = "商品 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/goodsExcelView")
    public Result goodsView(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<GoodsExcelDTO> list = EasyExcelUtil.read(url.openStream(), GoodsExcelDTO.class,2);
            if(CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<GoodsExcelVO> goodsExcelVoS = iGoodsService.goodsExcelView(list);
            return new Result().data(goodsExcelVoS);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 预览后导入库位
     * @param importCode 预览时生成的导入码
     * @param request
     * @return
     */
    @ApiOperation(value = "商品 导入", notes = "商品 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importGoods")
    public Result importGoods(@RequestParam("importCode") String importCode, HttpServletRequest request) {
        try {
            Result result = iGoodsService.importGoods(importCode);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "根据商品名称、编码模糊查询货主商品", notes = "根据商品名称、编码模糊查询货主商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "goodCode", value = "商品编码", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "goodsName", value = "商品名称", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/searchByGoodCodeAndName")
    public Result searchByGoodCodeAndName(@RequestParam(value = "goodCode", defaultValue = "") String goodCode,@RequestParam(value = "goodsName",defaultValue = "") String goodsName, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            String groupCode = UserUtil.getBranchCode();
            List<String> shipmentCodes = authMap.get(CommonConst.SHIPMENT_CODES);
            List<Map<String, Object>> result = iGoodsService.searchByGoodCodeAndName(goodCode,goodsName,groupCode,shipmentCodes);
            return Result.ok().data(result);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
}
